package tech.xs.workflow.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tech.xs.common.framework.domain.entity.BaseEntity;
import tech.xs.common.framework.service.CrudServiceImpl;
import tech.xs.common.framework.util.Assert;
import tech.xs.workflow.bpmn.BpmnElementHelper;
import tech.xs.workflow.bpmn.element.ProcessElement;
import tech.xs.workflow.dao.WorkflowDefineDao;
import tech.xs.workflow.domain.entity.BpmnProcess;
import tech.xs.workflow.domain.entity.WorkflowDefine;
import tech.xs.workflow.domain.entity.WorkflowTask;
import tech.xs.workflow.service.BpmnEventService;
import tech.xs.workflow.service.BpmnProcessService;
import tech.xs.workflow.service.BpmnSequenceFlowService;
import tech.xs.workflow.service.WorkflowDefineService;

import javax.annotation.Resource;

@Slf4j
@Service
public class WorkflowDefineServiceImpl extends CrudServiceImpl<WorkflowDefineDao, WorkflowDefine> implements WorkflowDefineService {

    @Resource
    private WorkflowDefineDao workflowDefineDao;
    @Resource
    private BpmnProcessService bpmnProcessService;
    @Resource
    private BpmnSequenceFlowService bpmnSequenceFlowService;
    @Resource
    private BpmnEventService bpmnEventService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void importWorkflow(Long id, String content) {
        WorkflowDefine workflowDefine = workflowDefineDao.selectById(id);
        Assert.isNotNull(workflowDefine, "流程不存在 流程定义id:" + id);
        ProcessElement processElement = BpmnElementHelper.analyze(content);
        BpmnProcess bpmnProcess = bpmnProcessService.importProcess(processElement);
        bpmnEventService.importEvent(bpmnProcess, processElement);
        bpmnSequenceFlowService.importSequenceFlow(bpmnProcess, processElement);
        workflowDefineDao.update(new WorkflowDefine(), Wrappers.<WorkflowDefine>lambdaUpdate()
                .set(WorkflowDefine::getBpmnId, bpmnProcess.getId())
                .eq(BaseEntity::getId, id)
        );
    }



}
